// 多谢几遍，记住
//1.导入模块 
//1.1 express 
const express = require('express'); 
//1.2 body-parser 
const bodyParser = require('body-parser'); 
const {readFileSync,writeFileSync} = require('fs')
const {resolve} = require('path')
//2.实例化对象 
let app = express(); 
//3.使用中间件
//3.1 解析表单格式的参数 
app.use(bodyParser.urlencoded({extended:true})); 
//3.2 解析json格式的参数
app.use(bodyParser.json()); 

app.all('*',(req,res,next)=>{
	res.header('Access-Control-Allow-Origin','*');
	res.header('Access-Control-Allow-Headers','Content-Type,Content-Length, Authorization, Accept,X-Requested-With');
	res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');
	next();
})
// 静态的数据
const duration = JSON.parse(readFileSync(resolve(__dirname,'data','duration.json'),'utf-8'))
const course = JSON.parse(readFileSync(resolve(__dirname,'data','course.json'),'utf-8'))
const teacher = JSON.parse(readFileSync(resolve(__dirname,'data','teacher.json'),'utf-8'))
//动态的数据

app.get('/initial_data',(req,res)=>{
    const schedule = JSON.parse(readFileSync(resolve(__dirname, 'data', 'schedule.json'), 'utf-8'))
    res.json({
        code:0,
        msg:'ok',
        data:{
            schedule,
            duration,
            course,
            teacher
        }
    })
})
app.post('/update_schedule',(req, res)=>{
    const {begin_time,weekday,course,teacher} = req.body.data
   const schedule = JSON.parse(readFileSync(resolve(__dirname, 'data', 'schedule.json'), 'utf-8'))
   const item = schedule.find(item=>item.begin_time==begin_time&&item.weekday==weekday)

   let type =''
   let result = null
   if(item){
    item.course = course
    item.teacher = teacher
    result = item
    type = 'EDIT'
   }else{
    let lastId = schedule[schedule.length-1] ? schedule[schedule.length-1].id :1
    const newData ={
        id:++lastId,
        begin_time,
        weekday,
        course,
        teacher
    }
    schedule.push(newData)
    result = newData
    type = 'ADD'
   }
   writeFileSync(resolve(__dirname, 'data', 'schedule.json'), JSON.stringify(schedule))
   res.json({
    code:0,
    msg:'ok',
    data:{
        type,
        result
    }
   })
})
app.post('/remove_schedule',(req, res)=>{
    const id = req.body.id
    const schedule = JSON.parse(readFileSync(resolve(__dirname, 'data', 'schedule.json'), 'utf-8'))
    const result = schedule.filter(item=>item.id!=id)
    writeFileSync(resolve(__dirname, 'data', 'schedule.json'), JSON.stringify(result))
    res.json({
        code:0,
        msg:'ok',
        data:{
            type:'REMOVE',
            id //id
        }
    })
})
//4.监听端口 
app.listen(3000,()=>{ 	
	console.log('server is running at port 3000')
})